// pages/address_list/address_list.js
const db = wx.cloud.database()
Page({
  data: {
    addressList: [],
    all: [],
    selectVal: {},
    nSelectval: {},
    kx: false
  },
  onLoad: function (options) {
    var openId = wx.getStorageSync('openId');
    let p1 = new Promise((resolve, reject) => {
      db.collection('address').where({
        _openid: openId
      }).get().then(res => {
        var a = res.data;
        resolve(a);
      })
    })
    Promise.all([p1]).then((result) => {
      let t = result[0];
      if (t.length == 0) {
        wx.showToast({
          title: '地址列为空！',
          duration: 1000,
          icon: 'error'
        })
      } else {
        var arrli = [];
        for (let i = 0; i < t.length; i++) {
          var b = t[i].str;
          arrli.push(b)
        }
        this.setData({
          addressList: arrli,
          all: t
        });
      }
    })
  },
  rachange: function (e) {
    this.selectVal = e.detail.value;
    var selectVal = this.selectVal;
    this.setData({
      selectVal,
    })
  },
  radiotap: function (e) {
    var nS = this.data.nSelectval;
    nS[e.currentTarget.dataset.gname] = this.selectVal;  /*微信学堂学的方法*/
    var choseAdd = nS.addre;
    var all = this.data.all;
    for (let i = 0, len = all.length; i < len; ++i) {
      if ((all[i].str.num) == choseAdd) {
        let id = all[i]._id;
        db.collection('address').doc(id).update({
          data: {
            'str.selected': true
          }
        })
      } else if ((all[i].str.num) != choseAdd) {
        let nid = all[i]._id;
        db.collection('address').doc(nid).update({      /*只支持两个地址*/
          data: {
            'str.selected': false
          }
        })
      }
    }
  },
  addAddress: function () {
    var openId = wx.getStorageSync('openId');
    db.collection('address').where({
      _openid: openId
    }).get().then(res => {
      var resAll = res.data;
      if (resAll.length < 2) {
        wx.navigateTo({
          url: '../address/address'
        });
      } else {
        wx.showToast({
          title: '暂只支持两地址！',
          duration: 2000
        })
      }
    })
  },
  delAddress: function (e) {
    var nS = this.data.selectVal;
    var all = this.data.all;
    for (let i = 0, len = all.length; i < len; ++i) {
      if ((all[i].str.num) == nS) {
        let id = all[i]._id;
        db.collection('address').doc(id).remove({})
        wx.showModal({
          title: '',
          content: '地址已删除！',
          showCancel: false,
        })
        setTimeout(() => {
          wx.switchTab({
            url: '../my/my'
          })  
        }, 1500);

      }
    }
  }
})